home *** CD-ROM | disk | FTP | other *** search
- Path: news.mira.net.au!news
- From: davidw@werple.net.au (David White)
- Newsgroups: comp.lang.c++
- Subject: Re: NEWBIE: Returning 0 as refernce
- Date: 16 Mar 1996 00:47:44 +1100
- Organization: Werple Internet, Melbourne
- Message-ID: <4ibse0$369@werple.net.au>
- References: <4huslk$rpk@badger.wmin.ac.uk> <4hvglg$v4@news4.digex.net> <4hvnbv$2rl@werple.net.au> <4iabdj$r89@news.ot.centuryinter.net>
- NNTP-Posting-Host: werplez.mira.net.au
-
- steidl@centuryineter.net writes:
-
- >In <4hvnbv$2rl@werple.net.au>, davidw@werple.net.au (David White) writes:
- >..
- >>I think he wants to know how to return a null reference. The answer is,
- >>you can't. In any case, there will be no difference in speed between
-
- >I don't seem to have any problem returning a null reference. Using
- >gcc ported for OS/2 I tested the following program and it compiled
- >without errors (or even warnings) and worked as expected. To create
- >a null reference dereference a null pointer, and to test if a reference is
- >null, take its address and compare it to a null pointer. (I don't know if
- >this violates some C++ rule, but it works on every compiler I've used.)
-
- >-------------------------------------------------
-
- >#include <stdio.h>
- >#include <stdlib.h>
-
- >int &foo() {
- > // more stuff could go here
- > return *((int *)0); // foo decides to return the "standard error-value"
- >};
-
- >int main() {
- > int &q = foo();
- > if (&q == (int *)0) {
- > printf("Successfully got null reference\n");
- > };
- > return 0;
- >};
-
- This works because compilers implement references as pointers. It is not
- supported by C++. A reference is an alias for an object. There is no such
- thing as a null 'int', for example, so there is no such thing as a null
- reference to an 'int'. The effect of dereferencing a null pointer, as
- shown above, is undefined.
-
- David White
- davidw@werple.mira.net.au
-
-